<?php
/***
 * created by tommy 2024-04-11
 * 
 * 
 */ 
namespace App\Http\Controllers\Api\Device;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use GuzzleHttp\Client;
use App\Helpers\RedisKeyUtil;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Response;
use App\Http\Controllers\Api\Device\BaseApi;
use Illuminate\Support\Facades\Redis;

/**
 * Class for Xishuashua api.
 * 小雨嘀嗒接口说明:
 * 

 */
class XYApi extends BaseApi
{

    private static $_instance;

    //接口url
    public  $url                = 'http://api.gdymdz.com';
    //令牌
    public  $key                = '6c2cd19b8e';
    //操作员帐号
    public  $username           = '13928582063';
    //操作员密码
    public  $password           = 'G8Si2bx3303';

    
    //private function __construct() {}
    
    public static function getInstance() {
        if (empty(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    
    //private function __clone() {}
    
    /**
     * 获得Token接口
     * 
     */ 
    public function GetToken()
    {
        $token = Redis::get("xss_token");
        if (empty($token)){
            $path  = $this->url.'/Api/Index/getToken';
            $param = [];
            $token = "";
            $res   = $this->CurlGet($path, $param);
            if ($res['code'] == 1){
                $token = $res['token'];
                Redis::setex("xss_token" , 86400 , $token);
            }else{
                $token = "";
                $this->log(' post error '.$path.", result:", $res, 'YM');

            } 
        }

        return $token;
    }
    
    /**
     * 洗涮涮加密方法，对方文档里面提供
     * @param string $json 待加密的json字符串
     * @param string $key     密钥
     * 
     * @param Sting $base64   返回加密后的字符串
     */
    public function EntyEncode($json)
    {
        $rand_num = rand(0, 100000);
        $mixStr = md5($this->key . $rand_num);
        $tmp = '';
        $strLen = strlen($json);
        for ($i = 0, $j = 0; $i < $strLen; $i++, $j++) {
            $j = $j == 32 ? 0 : $j;
            $tmp .= $mixStr[$j] . ($json[$i] ^ $mixStr[$j]);
        }
        $base64 = base64_encode($tmp);
        return $base64;
    }

    /**
     * 获得随机字符串 nonce_str
     * @param [type] $prefix [description]
     */
    private function RandStr($prefix ='')
    {
        return strtoupper(md5(uniqid($prefix)));
    }

    /**
     * 获得订单号
     */
    private function OrderSN($prefix = '')
    {
        $order_sn = $prefix.date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        return $order_sn;
    }

    /**
     * 接口尾部追加token字符串
     * 
     * $param string $url 接口地址
     * 
     */
    public function AppendToken($url)
    {
        $token = $this->GetToken();
        $fullurl = $url."/token/".$token;
        return $fullurl;
    }

    /**
     * 会员启动设备,即用户先要注册成为会员
     * 
     * @param   string $device_no  设备编号
     * @return [type] [description]
     */
    public function MemberStartDevice($device_no, $phone)
    {
        $url = $this->url.'/Api/Machine/reBoot';
        $fullurl = $this->AppendToken($url);
        $param = [
                    'account'      => $this->username,//操作员帐号  
                    'acpwd'        => $this->password,//操作员密码
                    'phone'        => $phone,//用户手机号码  
                    'code'         => $device_no,//设备编号 
                    'uri'           => 'https://sdxiche.baiche.com.cn/api/member/device/start_callback',//会员启动机器后的回调地址
                ];
        $entydata = $this->EntyEncode($param);//加密
        //dd($param);
        //请求接口
        $result = $this->CurlPost($fullurl, ['data' => $entydata]);
        return $result;
    }

    /**
     * 查询单个设备状态
     * 返回结果 
     */
    public function DeviceStatus($device_no)
    {
        $url = $this->url.'/Api/Device/get_device';
        $fullurl = $this->AppendToken($url);
        $param = [
                    'account'      => $this->username,//操作员帐号  
                    'acpwd'        => $this->password,//操作员密码
                    'device'       => $device_no,//出币数量 
                ];
        $entydata = $this->EntyEncode(json_encode($param));//加密
        //请求接口
        $result = $this->CurlPost($fullurl, ['data' => $entydata]);
        return $result;
    }


    /**
     * 查询所有设备列表以及状态，主要是查询状态 API
     * 返回结果 ：
            {
                "code": 1,
                "msg": "查询成功！",
                "data": {
                    "list": [
                        {
                            "code": "2865077",
                            "name": "1020简易",
                            "usercode": "9991",
                            "type": "洗车机",
                            "address": "广州",
                            "status": "正常"
                        }
                    ],
                    "count": 1
                }
            }
     */
    public function GetDeviceList()
    {
        $url = $this->url.'/Api/Product/get_device_list';
        $fullurl = $this->AppendToken($url);
        $param = [
                    'account'      => $this->username,//操作员帐号  
                    'acpwd'        => $this->password,//操作员密码
                ];
        //dd(json_encode($param));
        $entydata = $this->EntyEncode(json_encode($param));//加密
        //dd($fullurl, $entydata);
        //请求接口
        $result = $this->CurlPost($fullurl, ['data' => $entydata]);
        //dd($result);
        return $result;
    }

    /**
     * 单次启动设备
     * 1.刚开始文档里面描述回调地址是机器收到信息后的回调，现在说是结算回调，文档描述的和沟通的不一致
     * 
     * 且按照沟通来看，流程不严谨，调用接口后，机器有没有收到信息我这边不知道，
     * 这样可能会造成因为网络或者潜在的问题造成我这边请求接口了，但机器没有收到信息的情况
     * 疑惑的是做硬件的应该会比较严谨才对，只能先这样了
     * 
     * @param int $order_id 订单号，必须是纯数字
     * @param string $device_no  设备编号 
     * @param float $money  金额
     * 
     */ 
    public function SignleStart($order_id, $device_no, $money)
    {
        $url = $this->url.'/Api/Device/index';
        $fullurl = $this->AppendToken($url);
        $param = [
                    'order_id'     => $order_id,//订单ID，必须是纯数字  
                    'user'         => $this->username,//操作员帐号  
                    'password'     => $this->password,//操作员密码
                    'device_no'    => $device_no,//设备编号
                    'money'        => $money,//金额
                    'res_url'      => 'https://sdxiche.baiche.com.cn/api/device/single_end_callback',//结算回调网址
                ];
        Log::info('yumai single start api, url:'.$url.',param :'.json_encode($param));
        $entydata = $this->EntyEncode(json_encode($param));//加密
        //请求接口
        $result = $this->CurlPost($fullurl, ['data' => $entydata]);

        return $result;
    }

    /**
     * 单次设备结算
     * 
     * @param int $order_id 订单号，纯数字
     * 
     * 
     */ 
    public function SignleStop($order_id)
    {
       $url = $this->url.'/Api/Orders/getorderdata';
        $fullurl = $this->AppendToken($url);
        $param = [
                    'order_id'     => $order_id,//订单ID，必须是纯数字  
                    'account'      => $this->username,//操作员帐号  
                    'acpwd'        => $this->password,//操作员密码
                ];
        $entydata = $this->EntyEncode(json_encode($param));//加密
        //请求接口
        $result = $this->CurlPost($fullurl, ['data' => $entydata]);

        return $result;
    }



    

  

}